package com.ruoyi.gpt.queue;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.domain.ChatRequestBo;
import com.ruoyi.common.utils.redis.QueueUtils;
import com.ruoyi.core.config.utils.OpenAiUtil;
import com.ruoyi.gpt.constants.QueueConstants;
import com.ruoyi.gpt.domain.bo.WxMsgBo;
import com.ruoyi.gpt.domain.vo.WxMsgVo;
import com.ruoyi.gpt.service.IWxMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;


@Component
@Slf4j
public class RequestHandler {
    @Autowired
    private IWxMsgService wxMsgService;
    @Autowired
    @Qualifier("threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    /**
     * 启动程序时启动线程监听用户队列获取用户请求然后消费
     */
    @PostConstruct
    public void run(){
        //创建线程池
        // ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS,new ArrayBlockingQueue<>(1000));
        // 从队列阻塞获取请求
        QueueUtils.subscribeBlockingQueue(QueueConstants.request,request -> {
            log.info("获取到请求：{}",request);
            ChatRequestBo chatRequestBo = BeanUtil.toBean(request, ChatRequestBo.class);
            // 获取apiKey
            String apiKey = String.valueOf(chatRequestBo.getApiKey());
            // 使用线程池进行处理
            threadPoolTaskExecutor.submit(()->{
                try {
                    // 处理请求
                    log.info("处理请求：{} --> 开始执行",chatRequestBo.getQuestion());
                    handleUserRequest(apiKey,chatRequestBo);
                    log.info("消费了apikey:{}处理请求：{} --> 执行结束",apiKey,chatRequestBo.getQuestion());
                } catch (Exception e) {
                    log.error("apikey: {} 处理请求：{} --> 执行异常",apiKey,chatRequestBo);
                }
            });
            log.info("处理请求 --> 执行结束等待下一个请求");

        });

//        QueueUtils.subscribeBlockingQueue(QueueConstants.apiKeys,key -> {
//            // 获取apiKey
//            String apiKey = String.valueOf(key);
//            // 使用线程池进行处理
//            threadPoolTaskExecutor.submit(()->{
//                // 从队列阻塞获取apiKey
//                ChatRequestBo chatRequestBo = QueueUtils.takeQueueObject(QueueConstants.request);
//                try {
//                    if(ObjectUtil.isNull(chatRequestBo)){
//                        return;
//                    }
//                    // 处理请求
//                    log.info("处理请求：{} --> 开始执行",chatRequestBo.getQuestion());
//                    handleUserRequest(apiKey,chatRequestBo);
//                    log.info("消费了apikey:{}处理请求：{} --> 执行结束",apiKey,chatRequestBo.getQuestion());
//                } catch (Exception e) {
//                    log.error("apikey: {} 处理请求：{} --> 执行异常",apiKey,chatRequestBo);
//                    // 设置已回答但请求出错
//                    // updateAnswer(chatRequestBo,"可以再说一次吗？，我没听清楚");
//                    // Websocket.sendInfo()发送消息
//                } finally {
//                    // 最后将apiKey放回队列
////                    log.info("将key放回队列：{} --> 放回队列",apiKey);
//                    QueueUtils.addQueueObject(QueueConstants.apiKeys,apiKey);
//                }
//            });
//        });
    }
    // 处理用户请求
    //定义为异步方法
    void handleUserRequest(String apiKey, ChatRequestBo chatRequestBo) {
        // 查询5分钟内的3条历史消息
        List<WxMsgVo> oldMsgList = wxMsgService.queryBackAndForthMsgList(chatRequestBo.getUserId());

        //拼接完成后发送请求
        OpenAiUtil.sendRequest(chatRequestBo,"http://3.36.56.108:7501/",apiKey,oldMsgList);
    }
    // 更新回答
    private WxMsgVo updateAnswer(ChatRequestBo chatRequestBo, String answer) {
        WxMsgBo wxMsg = new WxMsgBo();
        wxMsg.setDetail(chatRequestBo.getQuestion()); // 设置问题
        wxMsg.setRepContent(answer); // 设置回复内容
        wxMsg.setResponseTime(String.valueOf(System.currentTimeMillis())); // 设置回复时间
        wxMsg.setInOut("2"); // 设置回复类型 2是双向
        wxMsg.setOpenid(chatRequestBo.getOpenId()); // 设置用户openId
        wxMsg.setAppid(chatRequestBo.getAppid()); // 设置用户appId
        wxMsg.setUserId(chatRequestBo.getUserId()); // 设置用户id
        // 设置响应时间
        wxMsg.setResponseTime(DateUtil.between(chatRequestBo.getCreateTime(), DateUtil.date(), DateUnit.SECOND) +"");
        wxMsgService.insertByBo(wxMsg);
        return BeanUtil.toBean(wxMsg, WxMsgVo.class);
    }
}
